<?php

namespace app\controllers\scan;

use app\models\Driver;
use app\models\MergeOrderPrintQueue;
use app\models\Order;
use app\models\OrderItem;
use app\models\OrderOpenantReturn;
use app\models\User;
use app\models\Warehouse;

/**
 *
 * 扫码出/入库, 全是子订单(一个商家一个订单)
 *
 * Class IndexController
 * @package app\controllers\scan
 */
class IndexController extends ScanBaseController
{
    // 状态
    const INTO = 1;
    const OUT = 2;


    /**
     * login
     *
     */
    public function actionLogin()
    {
        $data = $this->post();
        if (empty($data['phone']) || empty($data['password'])) {
            return $this->fail('请输入账号或密码');
        }
        $model = Driver::find()
            ->where(['driver_name' => $data['phone'], 'password' => md5($data['password'])])
            ->one();
        if (empty($model)) {
            return $this->fail('账号或密码错误');
        }
        if ($model->status === 0) {
            return $this->fail('账号已被禁用');
        }
        $model = $model->toArray();
        unset($model['password']);
        return $this->success($model);
    }


    /**
     * into
     */
    public function actionInto()
    {
        $transaction = \Yii::$app->db->beginTransaction();

        // file_put_contents('aa.txt', time() . json_encode($this->post()) . PHP_EOL, FILE_APPEND);

        try {
            $data = $this->post();

            if (empty($data)) {
                throw new \Exception('error');
            }

            $order_id = $data['order_id'];
            $order_sn = isset($data['order_sn']) ? $data['order_sn'] : '';
            //是否合单打单订单
            $model = MergeOrderPrintQueue::find()->where(['sn' => $order_sn])->asArray()->all(); //$model = MergeOrderPrintQueue::find()->where(['id' => $order_id])->one();
            if ($model) {
                $oids = [];
                foreach ($model as $v) {
                    $oids[] = $v['order_sn'];
                }
                $model = Order::find()
                    ->where(['in', 'order_id', $oids])
                    // ->where("order_id = {$order_id} for update")
                    // ->with(['item'])
                    // ->asArray()
                    ->all();
            } else {
                $model = Order::find()
                    ->where(['order_id' => $order_id])
                    // ->where("order_id = {$order_id} for update")
                    // ->with(['item'])
                    // ->asArray()
                    ->all();
            }

            if (!$model) {
                throw new \Exception('订单错误');
            }
            $isReturnGoodsList = [];
            $totalOrderNum = 0;
            $goodsList = [];
            foreach ($model as $orderModel) {
                if ($orderModel->status == -99) {
                    throw new \Exception('订单已经被取消,如合单，请重新打单');
                }

                if ($orderModel->status == self::INTO) {
                    throw new \Exception('商品已经入过库了');
                }

                if ($orderModel->status != 0) {
                    throw new \Exception('订单状态不对无法入库：' . $orderModel->status);
                }

                if (!$orderModel->in_json) {
                    $into = [];
                } else {
                    $into = json_decode($orderModel->in_json, true);
                }
                if (!empty($into)) {
                    if (in_array($data['current'], $into['num'])) {
                        throw new \Exception('此包已经入过库了');
                    }
                }


                // array_push($into, $data['current']);
                $into['num'][] = $data['current'];
                $into['time'][] = date('Y-m-d H:i:s');
                if (count($into['num']) >= $orderModel->total_quantity) {
                    $orderModel->status = self::INTO;
                    $orderModel->in_json = json_encode($into);
                    $message = '入库成功, 总共( ' . $orderModel->total_quantity . ' )件';
                    $status = 1;
                    // 处理总订单状态
                    if ($orderModel->parent_id > 0) {
                        $count = Order::find()
                            ->where(['parent_id' => $orderModel->parent_id])
                            // ->andWhere(['!=', 'status', -99])
                            ->count();
                        $count2 = Order::find()
                            ->where(['parent_id' => $orderModel->parent_id])
                            ->andWhere(['status' => self::INTO])
                            ->count();
                        // return $this->success([
                        //     'a' => [$count, $count2]
                        // ]);
                        // 由于事务还没有提交, 需要加1
                        if ($count == $count2 + 1) {
                            $parent = Order::find()
                                ->where(['order_id' => $orderModel->parent_id])
                                ->one();
                            $parent->status = self::INTO;
                            $parent->save();
                        }
                    }
                } else {
                    // $into['time'][] =date('Y-m-d H:i:s'); 
                    $orderModel->in_json = json_encode($into);
                    $message = '入库成功, 当前第( ' . $data['current'] . ' )件, 总共: ' . $orderModel->total_quantity . ' 件';
                    $status = 0;
                }

                $orderModel->save();

                $list = OrderItem::find()
                    ->where(['order_id' => $orderModel->order_id])
                    ->with(['product'])
                    ->asArray()
                    ->all();
                foreach ($list as $item) {
                    $item['quantity'] = $item['goods_num'];
                    $item['name'] = $item['product']['goods_name'];
                    $goodsList[] = $item;
                }


                $isReturnGoods = OrderOpenantReturn::find()
                    ->where(['order_id' => $orderModel->order_id])
                    ->with(['product'])
                    ->asArray()
                    ->all();
                foreach ($isReturnGoods as $v) {
                    $v['quantity'] = $v['goods_num'];
                    $v['name'] = $v['product']['goods_name'];
                    $isReturnGoodsList[] = $v;
                }
                // $isReturnGoodsList[] = $isReturnGoods;
                $totalOrderNum += $orderModel->order_num;
            }
            $transaction->commit();
            return $this->success([
                'order' => [
                    'total' => $totalOrderNum, //$model->order_num,
                    'list' => $goodsList, //$list,
                    'return_goods' => $isReturnGoodsList
                ],
                'message' => $message,
                'status' => $status,
                'type' => empty($isReturnGoods) ? 1 : 2
            ]);
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage() . $e->getLine());
            // return $this->fail(json_encode([
            //     'msg' => $e->getMessage(),
            //     'line' => $e->getLine()
            // ]));
        }
    }

    /**
     * out
     */
    public function actionOut()
    {
        $transaction = \Yii::$app->db->beginTransaction();

        // file_put_contents('bb.txt', time() . json_encode($this->post()) . PHP_EOL, FILE_APPEND);

        try {
            $data = $this->post();

            if (empty($data)) {
                throw new \Exception('error');
            }

            $order_id = $data['order_id'];
            $order_sn = isset($data['order_sn']) ? $data['order_sn'] : '';
            // $model = Order::find()
            //     ->where(['order_id' => $order_id])
            //     // ->where("order_id = {$order_id} for update")
            //     // ->with(['item'])
            //     // ->asArray()
            //     ->one();
            $model = MergeOrderPrintQueue::find()->where(['sn' => $order_sn])->asArray()->all();
            if ($model) {
                $oids = [];
                foreach ($model as $v) {
                    $oids[] = $v['order_sn'];
                }
                $model = Order::find()
                    ->where(['in', 'order_id', $oids])
                    // ->where("order_id = {$order_id} for update")
                    // ->with(['item'])
                    // ->asArray()
                    ->all();
            } else {
                $model = Order::find()
                    ->where(['order_id' => $order_id])
                    // ->where("order_id = {$order_id} for update")
                    // ->with(['item'])
                    // ->asArray()
                    ->all();
            }
            if (!$model) {
                throw new \Exception('订单错误');
            }
            $totalNum = 0;
            $totalGoodsList = [];
            foreach ($model as $orderModel) {
                if ($orderModel->status == -99) {
                    throw new \Exception('订单已经被取消');
                }



                if ($orderModel->status == self::OUT) {
                    throw new \Exception('商品已经出过库了');
                }


                if ($orderModel->status != self::INTO) {
                    throw new \Exception('商品还没有入库');
                }

                if ($orderModel->status != 1) {
                    throw new \Exception('订单状态不对：' . $orderModel->status);
                }

                $driverLineId = Driver::find()
                    ->where(['driver_id' => $data['driver_id']])
                    ->one();
                if (empty($driverLineId)) {
                    throw new \Exception('司机账号暂无线路' . $orderModel->status);
                }
                $userLineId = User::find()->where(['user_id' => $orderModel->user_id])->one();
                $tmpUserLineId = Warehouse::find()->where(['warehouse_name' => $userLineId['check']])->one();
                if (empty($tmpUserLineId)) {
                    throw new \Exception('用户账号暂无线路' . $orderModel->status);
                }
                if ($driverLineId['is_type'] == 1) {

                    $driverLineId['line_config'] = json_decode($driverLineId['line_config'], true);
                    $tmpLineConfig = empty($driverLineId['line_config']) ? [] : $driverLineId['line_config'];
                    $tmpLineConfig[] = $driverLineId['line_id'];
                    if (!in_array($tmpUserLineId['line_id'], $tmpLineConfig)) {
                        throw new \Exception('线路不对');
                    }
                    // if ($driverLineId['line_id'] != $tmpUserLineId['line_id']) {
                    //     throw new \Exception('线路不对');
                    // }
                }


                if (!$orderModel->out_json) {
                    $out = [];
                } else {
                    $out = json_decode($orderModel->out_json, true);
                }
                if (!empty($out)) {
                    if (in_array($data['current'], $out['num'])) {
                        throw new \Exception('此包已经出过库了');
                    }
                }
                $out['num'][] =  $data['current'];
                // array_push($out, $data['current']);
                $out['time'][] = date('Y-m-d H:i:s');
                $out['driver'][] = $driverLineId['real_name'];
                if (count($out['num']) >= $orderModel->total_quantity) {
                    $orderModel->status = self::OUT;
                    // $model->out_json = '';

                    $orderModel->out_json = json_encode($out, JSON_UNESCAPED_UNICODE);
                    $message = '出库成功, 总共( ' . $orderModel->total_quantity . ' )件';
                    $status = 1;

                    // 处理总订单状态
                    // if ($orderModel->parent_id > 0) {

                    // }
                    // $count = Order::find()
                    // ->where(['parent_id' => $orderModel->parent_id])
                    // // ->andWhere(['!=', 'status', -99])
                    // ->count();
                    // $count2 = Order::find()
                    //     ->where(['parent_id' => $orderModel->parent_id])
                    //     ->andWhere(['status' => self::OUT])
                    //     ->count();
                    // return $this->success([
                    //     'a' => [$count, $count2]
                    // ]);
                    // 由于事务还没有提交, 需要加1
                    // if ($count == $count2 + 1) {
                    //     $parent = Order::find()
                    //         ->where(['order_id' => $orderModel->parent_id])
                    //         ->one();
                    //     $parent->status = self::OUT;
                    //     $parent->save();
                    // }

                } else {
                    // $out['time'][]= date('Y-m-d H:i:s');
                    $orderModel->out_json = json_encode($out, JSON_UNESCAPED_UNICODE);
                    $message = '出库成功, 当前第( ' . $data['current'] . ' )件, 总共: ' . $orderModel->total_quantity . ' 件';
                    $status = 0;
                }

                // status 05-13
                $parent = Order::find()
                    ->where(['order_id' => $orderModel->parent_id])
                    ->one();
                $parent->status = self::OUT;
                $parent->save();

                $orderModel->save();

                $list = OrderItem::find()
                    ->where(['order_id' => $orderModel->order_id])
                    ->with(['product'])
                    ->asArray()
                    ->all();
                foreach ($list as $item) {
                    $item['quantity'] = $item['goods_num'];
                    $item['name'] = $item['product']['goods_name'];
                    $totalGoodsList[] = $item;
                }
                // $totalGoodsList[] = $list; 
                $totalNum += $orderModel->order_num;
            }

            $transaction->commit();
            return $this->success([
                'order' => [
                    'total' => $totalNum,
                    'list' => $totalGoodsList
                ],
                'message' => $message,
                'status' => $status
            ]);
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }
    }
}
